import java.util.*;

public class 全排列II {

    //https://leetcode.cn/problems/permutations-ii/description/
    //dfs
    public static List<List<Integer>> ret;
    public static List<Integer> path;
    public static int n;
    public static boolean[] vis;
    public List<List<Integer>> permuteUnique(int[] nums) {
        n = nums.length;
        ret = new ArrayList<>();
        path = new ArrayList<>();
        vis = new boolean[n];
        Arrays.sort(nums);
        dfs(0,nums);
        return ret;
    }

    public void dfs(int pos,int[] nums) {
        if(pos == n){
            List<Integer> cur = new ArrayList<>(path);
            ret.add(cur);
            return;
        }
        for(int i = 0;i < n;i++){
            if(vis[i]) continue;//使用过就跳过
            if(i > 0 && nums[i] == nums[i - 1] && !vis[i - 1]){//如果上一个元素和下一个一样, 并且上一个元素没有使用过也跳过
                continue;
            }
            //回溯
            path.add(nums[i]);
            vis[i] = true;
            dfs(pos + 1,nums);
            path.remove(path.size() - 1);
            vis[i] = false;
        }
    }
}
